package com.shy.config.util;

import com.shy.config.common.TokenConstants;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
public class TokenManager {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 刷新token时间
     * @param token
     * @param rememberMe
     */
    @Async
    public void flushTokenTime(String token, Boolean rememberMe) {
        //获取token有效时常
        Long expire = stringRedisTemplate.getExpire(TokenConstants.TOKEN_PREFIX + token);
        //判断是否选择了记住我
        if (rememberMe){
            //选择记住我，刷新token时间
            //判断token剩余时常是否小于token的阈值
            if (expire < TokenConstants.REMEMBER_ME_REMEMBER_TIME){
                //小于，刷新token时间
                stringRedisTemplate.expire(TokenConstants.TOKEN_PREFIX + token, Duration.ofSeconds(TokenConstants.REMEMBER_ME_TIME));
            }
        }else {
            //未选择记住我，刷新token时间
            if (expire < TokenConstants.REMEMBER_TIME){
                stringRedisTemplate.expire(TokenConstants.TOKEN_PREFIX + token, Duration.ofSeconds(TokenConstants.TOKEN_TIME));
            }
        }
    }
}
